package com.liyu.rabbit.producer;

import com.liyu.rabbit.factory.RabbitFactory;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * @author 李誉
 * @date 2022-06-08 23:06
 * @description 主题交换机
 */
public class TopicProducer {

    public static final String TOPIC_EXCHANGE = "topic_ex";

    public static final String HELLO_QUEUE = "hello";

    public static final String HELLO_QUEUE2 = "hello2";

    public static void main(String[] args) throws IOException, TimeoutException {

        // 创建信道
        Channel channel = RabbitFactory.createNewChannel();

        // 开启发布确认
        channel.confirmSelect();

        // 添加发布确认监听
        ConfirmCallback ack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布成功。");
        };
        ConfirmCallback nack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布失败。");
        };
        channel.addConfirmListener( ack, nack);

        // 声明交换机
        channel.exchangeDeclare(TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC);

        // 声明队列: 队列名称， 是否持久化， 是否独占， 是否自动删除， 其他参数
        channel.queueDeclare(HELLO_QUEUE, true, false, false, null);
        channel.queueDeclare(HELLO_QUEUE2, true, false, false, null);

        // 绑定交换机和队列
        channel.queueBind(HELLO_QUEUE, TOPIC_EXCHANGE, "*." + HELLO_QUEUE + ".#");
        channel.queueBind(HELLO_QUEUE2, TOPIC_EXCHANGE, "#." + HELLO_QUEUE2 + ".#");

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入路由key:");
        String routingKey = null;
        String msg = null;
        while (scanner.hasNext()) {
            routingKey = scanner.next();
            if (routingKey == null || "".equals(routingKey)) {
                continue;
            }
            System.out.println("请输入发送的消息");
            msg = scanner.next();
            channel.basicPublish(TOPIC_EXCHANGE ,routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes(StandardCharsets.UTF_8));

            System.out.println("请输入路由key:");
        }

    }

}
